package com.example.administrator.appstpremvpdemo.view.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.appstpremvpdemo.R;
import com.example.administrator.appstpremvpdemo.helper.AEShelper;
import com.example.administrator.appstpremvpdemo.helper.ThreadPoolHelper;
import com.example.administrator.appstpremvpdemo.manager.LocalActivityManager;
import com.example.administrator.appstpremvpdemo.view.fragment.BaseFragment;
import com.example.administrator.appstpremvpdemo.view.fragment.Homefragent;
import com.example.administrator.appstpremvpdemo.view.fragment.Appfragent;
import com.example.administrator.appstpremvpdemo.view.fragment.Gamefragent;
import com.example.administrator.appstpremvpdemo.view.fragment.Userfragent;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2017/12/11
 * @description
 * @function
 */

public class MainActivity extends BaseActivity {

    private TabHost mTabhost;
    //private List<Tab> mTabs = new ArrayList<Tab>();
    private LayoutInflater minflater;
    private TabManager mTabManager;

    private static final Class<?>[] CLASSES = {Homefragent.class, Appfragent.class, Gamefragent.class, Userfragent.class};
    private int[] pics = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
    private int[] labels = {R.string.home, R.string.app, R.string.games, R.string.mine};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parseIntendData(getIntent());
        setContentView(R.layout.activity_maintab2);
        mTabhost = ((TabHost) findViewById(android.R.id.tabhost));
        mTabhost.setup();
        init();
        mTabManager.setCurrentTab(0);
        Log.w("MainActivity", "onCreate");
        Toast.makeText(this, LocalActivityManager.getInctance().getTopActivity().getLocalClassName(), Toast.LENGTH_SHORT).show();
    }

    /**
     *
     */
    private void init() {
        mTabManager = new TabManager(this, android.R.id.tabcontent, mTabhost);

        TabHost.TabSpec tabSpec;
        //创建tab
        for (int i = 0; i < CLASSES.length; i++) {
            tabSpec = mTabhost.newTabSpec(CLASSES[i].getName());
            tabSpec.setIndicator(getTabItemView(getString(labels[i]), pics[i]));
            mTabManager.addTab(tabSpec, CLASSES[i], null);
        }
    }

    private View getTabItemView(String string, int drawableRes) {
        View view = LayoutInflater.from(this).inflate(R.layout.home_tab_layout, null);
        ((ImageView) view.findViewById(R.id.iv)).setBackgroundResource(drawableRes);
        ((TextView) view.findViewById(R.id.tv)).setText(string);
        return view;
    }

    /**
     * tab管理类，管理fragment生命周期
     */
    public static class TabManager implements TabHost.OnTabChangeListener {
        private final FragmentActivity mActivity;
        private final int mcontainerId;
        private final TabHost mTabHost;
        private final Map<String, tabInfo> mTabMap = new HashMap<>();
        private tabInfo mLastTab;

        static final class tabInfo {
            private final String mTag;
            private BaseFragment fragment;
            private final Bundle args;
            private final Class<?> mClass;

            tabInfo(String tag, Bundle args, Class<?> aClass) {
                this.mTag = tag;
                this.args = args;
                mClass = aClass;
            }
        }

        static class tabFactory implements TabHost.TabContentFactory {

            private Context mContext;

            public tabFactory(Context context) {
                this.mContext = context;
            }

            @Override
            public View createTabContent(String tag) {

                TextView textView = new TextView(mContext);
                textView.setMinHeight(0);
                textView.setMinWidth(0);
                return textView;
            }
        }

        public TabManager(FragmentActivity activity, int mcontainerId, TabHost tabHost) {
            this.mActivity = activity;
            this.mcontainerId = mcontainerId;
            this.mTabHost = tabHost;
            mTabHost.setOnTabChangedListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clazz, Bundle agrs) {

            tabSpec.setContent(new tabFactory(mActivity));
            String tag = tabSpec.getTag();
            tabInfo tabInfo = new tabInfo(tag, agrs, clazz);
            tabInfo.fragment = ((BaseFragment) mActivity.getSupportFragmentManager().findFragmentByTag(tag));

            if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                ft.remove(tabInfo.fragment);
                ft.commitAllowingStateLoss();
                mActivity.getSupportFragmentManager().executePendingTransactions();
                tabInfo.fragment = null;
            }
            mTabMap.put(tag, tabInfo);
            mTabHost.addTab(tabSpec);
        }

        @Override
        public void onTabChanged(String tabId) {
            tabInfo newtab = mTabMap.get(tabId);
            //上一次点击的tab和当前的tab做对比
            if (mLastTab != newtab) {
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();

                //排除界面一开始，tab还都没被点击的情况
                if (mLastTab != null && mLastTab.fragment != null) {
                    ft.hide(mLastTab.fragment);
                }
                //当点击过
                if (newtab != null) {

                    if (newtab.fragment == null) {
                        newtab.fragment = ((BaseFragment) Fragment.instantiate(mActivity, newtab.mClass.getName()));
                        ft.add(mcontainerId, newtab.fragment, newtab.mTag);
                    } else {
                        if (newtab.fragment.isDetached()) {
                            ft.attach(newtab.fragment);
                        }
                        ft.show(newtab.fragment);
                    }
                }

                if (mLastTab != null && mLastTab.fragment != null) {
                    mLastTab.fragment.onPageHide();
                }

                if (newtab != null && newtab.fragment != null) {
                    newtab.fragment.onPageShow();
                }

                mLastTab = newtab;
                ft.commitAllowingStateLoss();
                mActivity.getSupportFragmentManager().executePendingTransactions();
            }
        }

        public void setCurrentTab(int id) {
            mTabHost.setCurrentTab(id);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
        Log.w("MainActivity", "ThreadPoolHelper.sThreadPoolExecutor.getActiveCount():" + ThreadPoolHelper.sThreadPoolExecutor.getActiveCount());
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        Toast.makeText(this, "onAttachedToWindow", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        parseIntendData(intent);
    }

    final String pwd = "helloworld1024";

    public void parseIntendData(Intent intent) {
        Uri uri = intent.getData();
        if (uri != null) {
            Log.w("2MainActivity", "uri:" + uri);
            String package_id = uri.getQueryParameter("package_id");
            String appFrom = uri.getQueryParameter("appFrom");

            //Toast.makeText(this, package_id, Toast.LENGTH_SHORT).show();

            String decrypt = AEShelper.decrypt(appFrom, pwd);

            Toast.makeText(this, "应用来源于："+decrypt, Toast.LENGTH_SHORT).show();
        }
    }
}
